#include "Upload.h"

namespace Upload {

Upload *Upload::instance()
{
    static Upload instance;
    return &instance;
}

Upload::Upload(QObject *parent)
    : QObject(parent), m_configurer(Configurer::instance()), m_running(false)
{
    createUploadHelpers();
}

Upload::~Upload()
{
    stop();
    qDeleteAll(m_uploadHelpers);
}

// 配置管理
QMap<QString, Config> Upload::getConfig() const { return m_configurer->getConfig(); }

bool Upload::setConfig(const QMap<QString, Config> &configMap)
{
    if (m_configurer->setConfig(configMap)) {
        updateUploadHelpers();
        emit configChanged();
        return true;
    }
    return false;
}

// 上传控制
void Upload::start()
{
    if (m_running) return;

    m_running = true;
    auto config = getConfig();
    for (auto it = config.begin(); it != config.end(); ++it) {
        if (it.value().enabled && m_uploadHelpers.contains(it.key())) {
            m_uploadHelpers[it.key()]->start();
            emit uploadStarted(it.key());
        }
    }
}

void Upload::stop()
{
    if (!m_running) return;

    m_running = false;
    for (auto helper : m_uploadHelpers) {
        helper->stop();
    }

    for (auto it = m_uploadHelpers.begin(); it != m_uploadHelpers.end(); ++it) {
        emit uploadStopped(it.key());
    }
}

// 状态查询
bool Upload::isRunning() const { return m_running; }

bool Upload::isRunning(const QString &key) const
{
    if (!m_running) return false;

    auto config = getConfig();
    if (!config.contains(key)) return false;

    return m_uploadHelpers.contains(key) && m_uploadHelpers[key]->isRunning();
}

// 私有方法
void Upload::createUploadHelpers()
{
    qDeleteAll(m_uploadHelpers);
    m_uploadHelpers.clear();

    auto config = getConfig();
    for (auto it = config.begin(); it != config.end(); ++it) {
        m_uploadHelpers[it.key()] = new UploadHelper(it.key(), it.value(), this);
    }
}

void Upload::updateUploadHelpers()
{
    // 停止并删除所有现有的UploadHelper
    for (auto it = m_uploadHelpers.begin(); it != m_uploadHelpers.end(); ++it) {
        it.value()->stop();
        delete it.value();
        emit uploadStopped(it.key());
    }
    m_uploadHelpers.clear();

    // 根据新配置重新创建所有UploadHelper
    auto config = getConfig();
    for (auto it = config.begin(); it != config.end(); ++it) {
        const QString &key = it.key();
        const Config &cfg = it.value();

        m_uploadHelpers[key] = new UploadHelper(key, cfg, this);

        // 如果系统运行且配置启用，启动上传
        if (m_running && cfg.enabled) {
            m_uploadHelpers[key]->start();
            emit uploadStarted(key);
        }
    }
}

}  // namespace Upload